package com.itheima.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itheima.bean.News;
import com.itheima.mapper.NewsMapper;
import com.itheima.service.NewsService;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

public class NewsServiceImpl implements NewsService {
    @Override
    public PageInfo<News> pageQuery(Integer currentPage, Integer pageSize) {
        SqlSession sqlSession = null;
        PageInfo<News> pageInfo = null;
        try {
            //1 加载mybatis的核心配置文件
            InputStream is = Resources.getResourceAsStream("MyBatisConfig.xml");
            //2 创建SqlSessionFactory对象
            SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);
            //3 获取SqlSession对象
            sqlSession = factory.openSession();
            //4 获取NewsMapper代理对象
            NewsMapper newsMapper = sqlSession.getMapper(NewsMapper.class);
            //5 执行查询操作
            //5.1 在执行查询之前设置分页参数:当前页数和每页条数
            PageHelper.startPage(currentPage,pageSize);
            //5.2 查询数据
            List<News> list = newsMapper.selectAll();
            //5.3 封装分页结果PageInfo
            pageInfo = new PageInfo<>(list);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //6 返回结果，释放资源
            sqlSession.close();
        }
        return pageInfo;
    }
}
